package com.tang.util;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 序列化工具类
 *
 * @author fulin.tang
 * @version V3.0
 * @since 2022/5/19 17:13
 */
public class SerializationUtil {

    private final Map<Class<?>, Schema<?>> cachedSchema;
    private final Objenesis objenesis;

    private static SerializationUtil instance;

    private SerializationUtil() {
        cachedSchema = new ConcurrentHashMap<>();
        objenesis = new ObjenesisStd();
    }

    public static SerializationUtil getInstance() {
        if (null != instance) return instance;
        synchronized (SerializationUtil.class) {
            if (null == instance) {
                instance = new SerializationUtil();
            }
        }
        return instance;
    }

    /**
     * 序列化（对象 -> 字节数组）
     *
     * @param obj 对象
     * @param <T> 对象类型
     * @return 字节数组
     */
    public <T> byte[] serialize(T obj) {
        Class<T> clazz = (Class<T>) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);// 512
        try {
            Schema<T> schema = this.getSchema(clazz);
            return ProtobufIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }

    /**
     * 反序列化（字节数组 -> 对象）
     *
     * @param data  字节数组
     * @param clazz 对象Class
     * @param <T>   对象类型
     * @return 对象
     */
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        try {
            T message = objenesis.newInstance(clazz);
            Schema<T> schema = this.getSchema(clazz);
            ProtobufIOUtil.mergeFrom(data, message, schema);
            return message;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    private <T> Schema<T> getSchema(Class<T> clazz) {
        Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
        if (schema == null) {
            schema = RuntimeSchema.createFrom(clazz);
            cachedSchema.put(clazz, schema);
        }
        return schema;
    }


}
